#!/usr/bin/perl -w # for syntax highlighting
# Take all the args and update portal ... and then
# redirect to page in the LP parameter.
use gri_secmgr qw(get_cookie_value redirect_header);
use gri_user_alert_config;
use gri_userprefs;
# use xml_helper;

sub mm_manage_prefs_process {
my $_aa=new xml_helper();

	my $url_prefix=$::GRI_FRONTEND->get_url_prefix();
	my $str="";
	my $user_stuff=get_cookie_value(name=>"gri_dbm_intranet");
	my @F=split(/\s+/,$user_stuff);
	my $user_name=$F[0];
	#########################################################
	# Abort if public user has attempted access.		#
	#########################################################
	if(!defined($user_name) || $user_name eq "public") {
		my $serror="Error Updating User Preferences";
		my $error="Failed to find the expected file '$users_dir/$user_name-prefs.xml'.";
		my $link="$url_prefix$::ENV{SCRIPT_NAME}/show_generic_error?serror=".string_to_hex($serror).",error=".string_to_hex($error).",previouspage=";
		redirect_header(path => $link);
		exit;
	}

	#########################################################
	# Load in the parameters and then change the details.	#
	#########################################################
	my $users_dir=$::GRI_FRONTEND->get_global_directory("users");
	if(! -f "$users_dir/$user_name-prefs.xml") {
		my $serror="Error Updating User Preferences";
		my $error="Failed to find the expected file '$users_dir/$user_name-prefs.xml'.";
		my $link="$url_prefix$::ENV{SCRIPT_NAME}/show_generic_error?serror=".string_to_hex($serror).",error=".string_to_hex($error).",previouspage=";
		redirect_header(path => $link);
		exit;
		return "";
	}
	my $xx=new gri_userprefs("$users_dir/$user_name-prefs.xml");
	if(!defined($xx)) {
		my $serror="Error Updating User Preferences";
		my $error="The system failed to read current user preference file.";
		my $link="$url_prefix$::ENV{SCRIPT_NAME}/show_generic_error?serror=".string_to_hex($serror).",error=".string_to_hex($error).",previouspage=";
		redirect_header(path => $link);
		exit;
	}

	#########################################################
	# Set all preferences...				#
	#########################################################
	for my $ckey (grep {/^def_/} (keys %::PARAM)) {
		my $cc=$ckey;
		$cc =~ s/^def_//;
		$xx->set_pref_value($cc,undef,$::PARAM{$ckey});
	}

	#########################################################
	# Write out user preferences.				#
	#########################################################
	my ($_rc,$_msg)=$xx->write();
	if($_rc==0) {
		my $serror="Error Updating User Preferences";
		my $error="Update of user preferences file failed during write: $_msg";
		my $link="$url_prefix$::ENV{SCRIPT_NAME}/show_generic_error?serror=".string_to_hex($serror).",error=".string_to_hex($error).",previouspage=";
		redirect_header(path => $link);
		exit;
	}
	my $link="$url_prefix$::ENV{SCRIPT_NAME}";
	redirect_header(path => $link);
	exit;
}

1;
